package cn.util.shiro.realm;

import javax.annotation.Resource;

import common.service.MryeDataCenterService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;


import java.util.*;

public class MyRealm extends AuthorizingRealm{

	@Resource(name="mryeDataCenterService")
	MryeDataCenterService mryeDataCenterService;

	/**
	 * 为当前登录的用户授予角色和权限
	 * @param principals
	 * @return
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO Auto-generated method stub
		String user_bh=(String)principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
		Map<String,Object> map=new HashMap<>();
		map.put("user_bh",user_bh);
		map.put("sql","select r.role_name from yst_user u,yst_role r where u.user_role_id=r.id and u.user_bh=#{user_bh}");
		authorizationInfo.setRoles(Collections.singleton(mryeDataCenterService.searchSap(map).get("role_name").toString()));
		map.put("sql","SELECT p.permission_name FROM yst_user u, yst_role r, yst_role_permission rp, yst_permission p WHERE u.user_role_id = r.id AND rp.role_id = r.id AND p.id = rp.permission_id AND u.user_bh = #{user_bh}");
		List<Map<String, Object>> listmap= mryeDataCenterService.searchSapList(map);
		Set<String> set=new HashSet();
		for (Map map1:listmap) {
			set.add(map1.get("permission_name").toString());
		}
		authorizationInfo.setStringPermissions(set);
		return authorizationInfo;
	}

	/**
	 * 验证当前登录的用户
	 * @param token
	 * @return
	 * @throws AuthenticationException
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// TODO Auto-generated method stub
		String user_bh=(String)token.getPrincipal();
		Map<String,Object> map=new HashMap<>();
		map.put("sql","select USER_BH,USER_PWD from yst_user where user_bh=#{user_bh}");
		map.put("user_bh",user_bh);
		map=mryeDataCenterService.searchSap(map);
		if(map!=null){
			AuthenticationInfo authcInfo=new SimpleAuthenticationInfo(map.get("USER_BH"),map.get("USER_PWD"),"xx");
			return authcInfo;
		}else{
			return null;
		}
	}
}


